package com.example.app;


import org.apache.zookeeper.*;
import org.apache.zookeeper.ZooDefs.Ids;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZookeeperClient implements Watcher {
    //连接超时时间,10s
    private static final int SESSION_TIMEOUT = 10000;
    //连接的zookeeperserver
    private static final String CONNECTION_STRING = "127.0.0.1:31811";
    private static final String ZK_PATH = "/qyktest";
    private ZooKeeper zk = null;
    private CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public void createConnection(String connectString, int sessionTimeout) {
        this.releaseConnection();
        try {
            zk = new ZooKeeper(connectString, sessionTimeout, this);
            connectedSemaphore.await();
        } catch (InterruptedException e) {
            System.out.println("连接创建失败，发生InterruptedException");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接创建失败，发生IOException");
            e.printStackTrace();
        }
    }

    public void releaseConnection() {
        if (this.zk != null) {
            try {
                this.zk.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean createPath(String path, String data) {
        try {
            String result = this.zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            System.out.println("节点创建成功,Path: " + result + ", content: " + data);
        } catch (KeeperException e) {
            System.out.println("节点创建失败，发生KeeperException");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("节点创建失败，发生InterruptedException");
            e.printStackTrace();
        }
        return true;
    }

    public String readData(String path) {
        try {
            System.out.println("获取数据成功，path：" + path);
            return new String(this.zk.getData(path, false, null));
        } catch (KeeperException e) {
            System.out.println("读取数据失败，发生KeeperException，path:" + path);
            e.printStackTrace();
            return "";
        } catch (InterruptedException e) {
            System.out.println("读取数据失败，发生InterruptedException，path: " + path);
            e.printStackTrace();
            return "";
        }
    }

    public boolean writeData(String path, String data) {
        try {
            System.out.println("更新数据成功，path：" + path + ", stat: " + this.zk.setData(path, data.getBytes(), -1));
        } catch (KeeperException e) {
            System.out.println("更新数据失败，发生KeeperException，path:" + path);
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("更新数据失败，发生InterruptedException，path: " + path);
            e.printStackTrace();
        }
        return false;
    }

    public void deleteNode(String path) {
        try {
            this.zk.delete(path, -1);
            System.out.println("删除节点成功，path：" + path);
        } catch (KeeperException e) {
            System.out.println("删除节点失败，发生KeeperException，path:" + path);
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("删除节点失败，发生InterruptedException，path: " + path);
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("收到事件通知：" + event.getState() + "\n");
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedSemaphore.countDown();
        }
    }

    public static void main(String[] args) {
        ZookeeperClient sample = new ZookeeperClient();
        //获取连接
        sample.createConnection(CONNECTION_STRING, SESSION_TIMEOUT);
        //读数据
//        String qyk = sample.readData("/qyktest");
//        System.out.println("qyk:" + qyk);
//        String url = sample.readData("/qyk/db/url");
//        System.out.println("url" + url);
//        String driver = sample.readData("/qyk/db/driver");
//        System.out.println("driver" + driver);
//        String userName = sample.readData("/qyk/db/userName");
//        System.out.println("userName" + userName);
//        String password = sample.readData("/qyk/db/password");
//        System.out.println("password" + password);
        //创建节点
        sample.createPath(ZK_PATH, "我是节点初始内容");
        System.out.println("数据内容:" + sample.readData(ZK_PATH) + "\n");
        //更新节点
        sample.writeData(ZK_PATH, "更新后的数据");
        System.out.println("数据内容:" + sample.readData(ZK_PATH) + "\n");
        //删除节点
        //sample.deleteNode(ZK_PATH);
        //释放连接
        sample.releaseConnection();
    }


}
